import { Component } from '@angular/core';
import { ApesField } from '@shared/ui-zorro/src/types/apes-field';
import { ApiService } from '@core/services/http/api.service';
import { Events } from '@core/services/events/Events';
import { ExpressionService } from '@core/services/expression/ExpressionService';
import { SubjectService } from '@core/services/events/subject.service';
import { deepClone, exists } from '../../../../utils/utils';
import { ApesContextMenuService } from '@shared/ag-grid-ext/context-menu';

@Component({
  selector: 'formly-field-link',
  template: `
    <apes-span [formControl]="formControl"
               [displayFormat]="display"
               [formlyAttributes]="field"
               (click)="openLink()"
               [ngClass]="{'apes-span-link': this.model[this.key]}"
               [ctx]="formState"></apes-span>
  `,
})
export class FormlyFieldLink extends ApesField {

  api: any;
  formId: any;
  form: any;
  value: any;

  constructor(
    protected apiService: ApiService,
    protected events: Events,
    protected expressionService: ExpressionService,
    protected subject: SubjectService,
    private contextService: ApesContextMenuService,
  ) {
    super(apiService, events, expressionService, subject);
  }

  ngOnInit() {
    this.api = this.to.api;
    this.formId = this.to.formId;
    // this.value = this.model[this.key];
  }

  get display() {
    return exists(this.to.valueFormatter) ? [this.to.valueFormatter] : ['value.name'];
  }

  openLink() {
    let value = this.model[this.key];
    if(!value) return;

    let api = this.expressionService.evaluate(this.api, {
      model: this.model,
    });

    let formId = this.expressionService.evaluate(this.formId, {
      model: this.model,
    });

    let sendData = {
      id : value
    };

    let config = {
      OAInterface: false,
      api: api
    };
    this.contextService.openContextLink(sendData, formId, config);
  }


}
